<template>
  <el-form
    ref="formRef"
    :model="pwdForm"
    :rules="rules"
    label-width="100px"
    style="max-width: 600px"
  >
    <!-- 原密码 -->
    <el-form-item label="原密码" prop="old_pwd">
      <el-input
        v-model="pwdForm.old_pwd"
        type="password"
        show-password
        placeholder="请输入原密码"
      />
    </el-form-item>

    <!-- 新密码 -->
    <el-form-item label="新密码" prop="new_pwd">
      <el-input
        v-model="pwdForm.new_pwd"
        type="password"
        show-password
        placeholder="请输入新密码"
      />
    </el-form-item>

    <!-- 确认密码 -->
    <el-form-item label="确认密码" prop="re_pwd">
      <el-input v-model="pwdForm.re_pwd" type="password" show-password placeholder="请确认新密码" />
    </el-form-item>

    <!-- 操作按钮 -->
    <el-form-item>
      <el-button type="primary" @click="submitForm">修改密码</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { updateUserPasswordService } from '@/api/user'
import router from '@/router'
import useUserStore from '@/stores/modules/user'
import { ref } from 'vue'

const useStore = useUserStore()

// 表单数据
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: '',
})

// 表单引用
const formRef = ref(null)

// 校验规则
const validateOldNewSame = (rule, value, callback) => {
  if (value === pwdForm.value.new_pwd) {
    callback(new Error('新密码不能与原密码相同'))
  } else {
    callback()
  }
}

const validatePwdSame = (rule, value, callback) => {
  if (value !== pwdForm.value.new_pwd) {
    callback(new Error('两次输入的新密码不一致'))
  } else {
    callback()
  }
}

const rules = {
  old_pwd: [
    { required: true, message: '原密码不能为空', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在6到15个字符', trigger: 'blur' },
    { validator: validateOldNewSame, trigger: 'blur' },
  ],
  new_pwd: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在6到15个字符', trigger: 'blur' },
  ],
  re_pwd: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    { validator: validatePwdSame, trigger: 'blur' },
  ],
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      // 这里处理提交逻辑
      console.log('提交数据：', pwdForm.value)
      // 调用接口
      await updateUserPasswordService(pwdForm.value)
      // 提示成功信息
      ElMessage.success('修改密码成功')
      // 移除token
      useStore.removeToken()
      // 重置用户信息
      useStore.user = {}
      // 跳转登录页
      router.push('/login')
    }
  })
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
}
</script>
